package com.iflytek.iot.common.utils;

import com.iflytek.iot.common.constants.Charset;

import java.io.UnsupportedEncodingException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author yu 2018/11/28.
 */
public class StringUtils {


    private StringUtils() {
        super();
    }

    /**
     *
     * @param str
     * @return
     */
    public static boolean isBlank(String str) {
        int strLen;
        if (str == null || (strLen = str.length()) == 0) {
            return true;
        }
        for (int i = 0; i < strLen; i++) {
            if ((Character.isWhitespace(str.charAt(i)) == false)) {
                return false;
            }
        }
        return true;
    }

    public static boolean isNotBlank(String str) {
        return !StringUtils.isBlank(str);
    }

    /**
     * 比较两个字符是否相等
     * @param str1
     * @param str2
     * @return
     */
    public static boolean equals(String str1, String str2) {
        return str1 == null ? str2 == null : str1.equals(str2);
    }

    /**
     * 判断字符是否为空
     * @param str
     * @return
     */
    public static boolean isEmpty(String str) {
        return str == null || "".equals(str) || str.length() == 0 || "null".equalsIgnoreCase(str);
    }

    /**
     * 判断字符非空
     * @param str
     * @return
     */
    public static boolean isNotEmpty(String str) {
        return !StringUtils.isEmpty(str);
    }

    /**
     * 字符串空格处理
     */
    public static final String trim(String value) {
        return value == null ? "" : value.trim();
    }

    /**
     * 判断字符串是否为空
     */
    public static boolean checkStringIsNull(String str) {
        return (str == null || str.length() == 0 || "".equals(str));
    }

    /**
     * Format null for string
     *
     * @param str
     */
    public static String formatNULL(String str) {
        if (str == null || "null".equalsIgnoreCase(str) || "".equals(str) || "undefined".equalsIgnoreCase(str)) {
            str = null;
        }
        return str;
    }

    /**
     * Format null for string[]
     *
     * @param str
     */
    public static String[] formatNULL(String[] str) {
        if (str == null || str.length < 1 || str[0] == null || "".equals(str[0])) {
            str = null;
        }
        return str;
    }

    /**
     * String key is include str
     *
     * @param key ..,..
     * @param str
     * @return boolean
     */
    public static boolean isInclude(String key, String str) {
        if (formatNULL(key) == null || formatNULL(str) == null) {
            return false;
        }
        return isInclude(key.split(","), str);
    }

    /**
     * String keys is include str
     *
     * @param keys
     * @param str
     * @return boolean
     */
    public static boolean isInclude(String[] keys, String str) {
        if (formatNULL(keys) != null && formatNULL(str) != null) {
            for (int i = 0, len = keys.length; i < len; i++) {
                if (str.equals(keys[i])) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 去掉字符串中的某个参数和值
     *
     * @param url
     * @param params
     * @return
     */
    public static String removeParams(String url, Object... params) {
        if (isBlank(url)) {
            return "";
        }
        String reg = null;
        StringBuffer ps = new StringBuffer();
        ps.append("(");
        for (int i = 0; i < params.length; i++) {
            ps.append(params[i]).append("|");
        }
        ps.deleteCharAt(ps.length() - 1);
        ps.append(")");
        // reg = "(?<=[\\?&])" + ps.toString() + "=[^&]*&?";
        // //这一行是匹配以?或者&符号开头的字符串
        // reg = ps.toString() + "=[^&]*&?";
        reg = ps.toString() + "=[^&]*";
        url = url.replaceAll(reg, "");
        url = url.replaceAll("(\\?|&+)$", "");
        return url;
    }

    /**
     * 字符串数组转字符串
     * @param arrays
     * @return
     */
    public static String array2String(String[] arrays) {
        StringBuffer sb = new StringBuffer("");
        for (int i = 0; i < arrays.length; i++) {
            String string = arrays[i];
            sb.append(string + (i == arrays.length - 1 ? "" : ","));
        }
        return sb.toString();
    }

    /**
     * 将数组转换为数组字符串以,隔开 中括号第一个属于特殊字符需要转义，第二个不属于特殊符号，不需要转义
     *
     * @param arrays
     * @return
     */
    public static String array2StringWithQuote(String[] arrays) {
        StringBuffer sb = new StringBuffer("(");
        for (int i = 0; i < arrays.length; i++) {
            String string = arrays[i];
            sb.append("'" + string + "'" + (i == arrays.length - 1 ? "" : ","));
        }
        sb.append(")");
        return sb.toString();
    }

    /**
     * 将Unicode转成中文
     *
     * @param unicode
     * @return
     */
    public static String unicode2String(String unicode) {
        Pattern pattern = Pattern.compile("(\\\\u(\\p{XDigit}{4}))");
        if (unicode == null) {
            return null;
        }
        Matcher matcher = pattern.matcher(unicode);
        char ch;
        while (matcher.find()) {
            ch = (char) Integer.parseInt(matcher.group(2), 16);
            unicode = unicode.replace(matcher.group(1), ch + "");
        }
        return unicode;
    }



    public static boolean hasText(String str) {
        return (hasLength(str) && containsText(str));
    }

    public static boolean hasLength(String str) {
        return (str != null && !str.isEmpty());
    }

    private static boolean containsText(CharSequence str) {
        int strLen = str.length();
        for (int i = 0; i < strLen; i++) {
            if (!Character.isWhitespace(str.charAt(i))) {
                return true;
            }
        }
        return false;
    }


    public static String newStringUtf8(final byte[] bytes) {
        try {
            return new String(bytes, Charset.DEFAULT_CHARSET);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static byte[] getBytesUtf8(final String string) {
        try {
            return string.getBytes(Charset.DEFAULT_CHARSET);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 生成流水号，例如：201806062117390002
     * 到达9**9后重新记号
     *
     * @param seq
     * @param len
     * @return
     */
    public static String orderNumber(long seq, int len){
        Double max = Math.pow(10, len) - 1;
        long maxLong = max.longValue();
        if (seq % maxLong > 0) {
            seq = seq % maxLong;
        }
        String b = String.valueOf(seq);
        StringBuilder builder = new StringBuilder();
        builder.append(DateUtils.nowStrTime());
        int rest = len - b.length();
        for (int i = 0; i < rest; i++) {
            builder.append("0");
        }
        builder.append(b);
        return builder.toString();
    }

    /**
     * 利用正则提取字符串
     * @param regex 正则式
     * @param source 源字符串
     * @return
     */
    public static String getMatcher(String regex, String source) {
        String result = "";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(source);
        while (matcher.find()) {
            result = matcher.group();
        }
        return result;
    }
}
